import { FC, useEffect, useCallback } from 'react';
import { Form, Input } from 'antd';
import type { FormInstance } from 'antd/lib/form';
import { useLocalStore } from 'mobx-react';

import Icons from '@components/Icons';
import { resetPasswordStore } from '@/stores/ResetPassword';

const ResetPasswordForm: FC = () => {
  const [resetPasswordForm] = Form.useForm<FormInstance>();
  const parentStore = useLocalStore(() => resetPasswordStore);

  const handleSetResetPasswordForm = useCallback(
    (form: FormInstance) => parentStore.setResetPasswordForm(form),
    []
  );

  useEffect(() => {
    handleSetResetPasswordForm(resetPasswordForm);
  }, [handleSetResetPasswordForm, resetPasswordForm]);

  return (
    <Form
      name="rb-find-password-second"
      form={resetPasswordForm}
      wrapperCol={{ offset: 3, span: 18 }}
    >
      <Form.Item
        name="password"
        rules={[
          {
            required: true,
            message: '请输入新的密码'
          }
        ]}
        hasFeedback
      >
        <Input.Password
          prefix={<Icons type="LockOutlined" style={{ color: 'rgb(24, 144, 255)' }} />}
          placeholder="请输入新的密码"
        />
      </Form.Item>

      <Form.Item
        name="confirm"
        dependencies={['password']}
        hasFeedback
        rules={[
          {
            required: true,
            message: '请再输入一次密码'
          },
          ({ getFieldValue }) => ({
            validator(_, value) {
              if (!value || getFieldValue('password') === value) {
                return Promise.resolve();
              }
              return Promise.reject(new Error('两次密码不一致!'));
            }
          })
        ]}
      >
        <Input.Password
          prefix={<Icons type="LockOutlined" style={{ color: 'rgb(24, 144, 255)' }} />}
          placeholder="确认密码"
        />
      </Form.Item>
    </Form>
  );
};

export default ResetPasswordForm;
